<?php
require 'db.php';
if (!isset($_GET['id'])) {
    header("Location: index.php");
    exit;
}

$settings = file_exists(__DIR__ . '/settings.json') ? json_decode(file_get_contents(__DIR__ . '/settings.json'), true) : ['file_expiry_days' => 0];
$file_id = filter_var($_GET['id'], FILTER_VALIDATE_INT);
if ($file_id === false) {
    header("Location: index.php");
    exit;
}

$stmt = $conn->prepare("SELECT path, name, upload_time FROM files WHERE id = ?");
$stmt->bind_param("i", $file_id);
$stmt->execute();
$result = $stmt->get_result();
if ($file = $result->fetch_assoc()) {
    $file_path = $file['path'];
    if ($settings['file_expiry_days'] > 0) {
        $upload_time = strtotime($file['upload_time']);
        $expiry_time = $upload_time + ($settings['file_expiry_days'] * 86400);
        if (time() > $expiry_time) {
            unlink($file_path);
            $stmt = $conn->prepare("DELETE FROM files WHERE id = ?");
            $stmt->bind_param("i", $file_id);
            $stmt->execute();
            echo "<script>alert('文件已过期！'); window.location.href='index.php';</script>";
            exit;
        }
    }
    if (file_exists($file_path)) {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file['name'] . '"');
        readfile($file_path);
        exit;
    } else {
        echo "<script>alert('文件不存在: " . htmlspecialchars($file_path) . "'); window.location.href='index.php';</script>";
    }
}
header("Location: index.php");
exit;
?>